<?php

class CompanyController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action controller here */
        $this->session_search_key = 'controller_company';
        $this->session_search_name = 'search_label';
        $this->list_sess_unset('controller_company');
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'company', '');
    }

    public function viewAction() {
        if ($this->_getParam('com_id') && $this->_getParam('com_id') != "") {
            $com_id = $this->_getParam('com_id');
        } else {
            $this->_helper->redirector('list', 'company', '');
        }
        $companyModel = new Model_Company();
        $companydata = $companyModel->fetchEntryById($com_id);
        $updated_id = $companydata['lgn_id'];
        $login_type = $companydata['lgn_type'];

        /*         * get user name which is updated data* */
        $loginModel = new Model_Login();
        $updated_by_user = $loginModel->getUserData(Array('lgn_id' => $updated_id));
        $user_name = ucfirst($updated_by_user->name) . " [" . ucfirst($updated_by_user->role) . "]";

        $this->view->admindata = $user_name;
        $this->view->companydata = $companydata;
    }

    public function listAction() {
        $errorMessage = Array();
        $successmessage = "";
        $where = "";
        $searchtype = "";
        $search_com_type = "";
        $orderField = 'com_id';
        $sort = 'asc';
        if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
        }


        /* Pagination Login */
        $itemsPerPageReviews = $this->PAGING_PER_PAGE;
        $currentPageReviews = 1;

        //PAGING_PER_PAGE

        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }

        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }

        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }


        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;

        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();

            //Multiple Delete Logic 
            if (isset($postedData["multiaction"]) && ($postedData["multiaction"] != "")) {
                $action = trim($postedData["multiaction"]);
                if (isset($postedData["multicheck"]) && count($postedData["multicheck"]) > 0) {
                    $ids = implode(",", $_POST["multicheck"]);
                    $result = $this->deleteAction($_POST["multicheck"]);
                } else {
                    $errorMessage[] = $this->ZFTRANSLATE->translate("select_one_checkbox"); #"Please select atleast one checkbox";
                }
            }

            /* Search Facility Over Here */
            if ($postedData["searchtype"] == "") {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
            }
            if (isset($postedData["searchtype"]) && ($postedData["searchtype"] != "")) {
                $searchtype = $postedData["searchtype"];
                if (strtolower($searchtype) == 'customer') {
                    $search_com_type = 2;
                } else if (strtolower($searchtype) == 'contractor') {
                    $search_com_type = 1;
                }
                $where = "com_name LIKE '%$searchtype%' OR com_phone LIKE '%$searchtype%' OR com_type = '$search_com_type' ";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = $searchtype;
                $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            }
        } else {
            $searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
            if (strtolower($searchtype) == 'customer') {
                $search_com_type = 2;
            } else if (strtolower($searchtype) == 'contractor') {
                $search_com_type = 1;
            }
            $where = "com_name LIKE '%$searchtype%' OR com_phone LIKE '%$searchtype%' OR com_type = '$search_com_type' ";
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = $searchtype;
            $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name];
        }


        $companyModel = new Model_Company();
        $companysData = $companyModel->fetchCompany($where, $itemsPerPageReviews, $offset, $orderField, $sort);

        $paginator = new GTL_Paginator();
        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($companyModel->getCompanyCount($where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('controller' => 'company', 'action' => 'list', 'page' => 'PAGENO'), 'default', false);
        $paginator->paginate($link);

        $this->view->paginator = $paginator;
        $this->view->companysData = $companysData;
        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;
        $this->view->statusArray = $companyModel->getStatusArray();
    }

    public function deleteAction($ids = Array()) {
        //Load Company Model 
        $companyModel = new Model_Company();
        if ($this->_getParam('com_id') && $this->_getParam('com_id') != "") {
            $com_id = $this->_getParam('com_id');
            $companyModel->deleteCompany($com_id);

            $this->addSuccessMessage($this->ZFTRANSLATE->translate("company_delete_success"));
            $this->_helper->redirector('list', 'company', '');
        } else {
            $companyModel->deleteCompany($ids);
            $this->addSuccessMessage($this->ZFTRANSLATE->translate("company_delete_success"));
            $this->_helper->redirector('list', 'company', '');
        }
    }

    public function formAction() {

        //Initialize
        $successmessage = "";
        $errorMessageArray = Array();
        $data = array();
        $companyData = Array();
        $this->view->mode = "Add";

        //Load Company Model
        $companyModel = new Model_Company();

        //Load Company Form
        $companyForm = new Form_CompanyForm();

        $imageName = "";

        //Load the company type array for the select box in form 
        $countryArray = $companyModel->getcountryArray();
        $companyForm->com_country->addMultiOptions($countryArray);


        //Load the company type array for the select box in form 
        $typeArray = $companyModel->getcompanytypeArray();
        $companyForm->com_type->addMultiOptions($typeArray);


        //Load the status array for the select box in form 
        $statusArray = $companyModel->getStatusArray();
        $companyForm->com_status->addMultiOptions($statusArray);



        //Check for the company Parameter
        $companyData['com_id'] = $this->_request->getParam('com_id');
        $com_id = (!empty($companyData['com_id'])) ? $companyData['com_id'] : null;

        if (!empty($com_id)) {
            //Set the Mode to Edit
            $this->view->mode = "Edit";
            //Fetch data to be loaded in form 
            $data = $companyModel->fetchEntryById($com_id);
            $imageName = $data['com_image'];
        }
        //Populate form 
        $this->view->form = $companyForm->populate($data);
        if ($this->getRequest()->isPost()) {
            //Check for Errors
            $postedData = $this->_request->getPost();
            if (!$companyForm->isValid($postedData)) {
                $errorMessage = $companyForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {
                if ($this->view->mode == "Add") {
                    //Image Validation
                    if ($_FILES['com_image']['name'] == '') {
                        $errorMessageArray[] = $this->ZFTRANSLATE->translate("company_required_image");
                    }
                }
                if ($_FILES['com_image']['name'] != '') {
                    $gtlObj = new GTL_Common();
                    $imageAllowedFormat = $gtlObj->allowedImageFormats();
                    $responseText = $gtlObj->image_validate($imageAllowedFormat, 'com_image');
                    if ($responseText == 'IMPROPER_FORMAT') {
                        $errorMessageArray[] = $this->ZFTRANSLATE->translate("company_required_valid_image"); #'Please upload image with valid file format.';
                    }
                }
                if (count($errorMessageArray) > 0) {
                    
                } else {
                    //Image upload
                    $upload = new Zend_File_Transfer_Adapter_Http();
                    foreach ($upload->getFileInfo() as $fields => $asFileInfo) {
                        if ($asFileInfo['name'] != '') {
                            $folder = $this->config->UPLOAD_PATH . "company/";
                            $upload->setDestination($folder);
                            $originalFilename = pathinfo($asFileInfo['name']);
                            $fileName = preg_replace("/[^-_a-zA-Z0-9]+/i", "_", $originalFilename['filename']) . '_' . time() . '.' . $originalFilename['extension'];
                            $upload->addFilter('Rename', $fileName, 'filename');
                            $upload->receive($fields);
                            $companyData['com_image'] = $fileName;
                        }
                    }

                    /*                     * authentication login id */
                    $defaultSession = new Zend_Session_Namespace(Zend_Registry::get('sessionName'));
                    $defaultSessionVal = $defaultSession->getIterator();
                    $updated_userid = $defaultSessionVal['storage']->lgn_id;

                    //Company save
                    $companyData['updated_lgn_id'] = $updated_userid;
                    $companyData['com_id'] = $com_id;
                    $companyData['com_name'] = $postedData['com_name'];
                    $companyData['com_phone'] = $postedData['com_phone'];
                    $companyData['com_fax'] = $postedData['com_fax'];
                    $companyData['com_address'] = $postedData['com_address'];
                    $companyData['com_city'] = $postedData['com_city'];
                    $companyData['com_state'] = $postedData['com_state'];
                    $companyData['com_country'] = $postedData['com_country'];
                    $companyData['com_zipcode'] = $postedData['com_zipcode'];
                    $companyData['com_type'] = $postedData['com_type'];
                    $companyData['com_status'] = $postedData['com_status'];
                    if ($this->view->mode == "Add") {
                        $companyData['com_createddate'] = date("Y-m-d H:i:s");
                    }
                    $companyData['com_updateddate'] = date("Y-m-d H:i:s");
                    $companyModel->save($companyData, 'com_id');
                    if ($this->view->mode == "Add") {
                        $successmessage = $this->ZFTRANSLATE->translate("company_add_success"); #"Company added successfully";
                    } else {
                        $successmessage = $this->ZFTRANSLATE->translate("company_update_success"); #"Company updated successfully";
                    }
                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'company', '');
                }
            }
        }
        $this->view->mode = $this->view->mode;
        $this->view->imageName = $imageName;
        $this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        $this->view->form = $companyForm;
    }

}

?>
